﻿using System;
using System.Collections.Generic;
using Toodledo.Model;
using System.Threading;
using Toodledo.Security;
using System.Collections.Specialized;
using Toodledo.Services.Interfaces;
using Toodledo.Services.Helpers;

namespace Toodledo.Services
{
    public class OrganizeService :ToodledoServiceBase
    {
        public OrganizeService(IToodledoConnector connector)
            : base(connector)
        {
        }

        public List<Folder> GetFolders()
        {
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                var currentIdentity = Thread.CurrentPrincipal.Identity as ToodledoIdentity;

                if (currentIdentity != null)
                {
                    var queryParams = new NameValueCollection {{"method", "getFolders"}, {"key", currentIdentity.AuthKey}};
                    var response = _toodledoConnector.GetToodledoResponse(queryParams);
                    return ToodledoExtensions.AsFolderList(response);
                }
            }
            throw new UnauthorizedAccessException("You are not signed in");
        }

        public List<Context> GetContexts()
        {
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                var currentIdentity = Thread.CurrentPrincipal.Identity as ToodledoIdentity;

                if (currentIdentity != null)
                {
                    var queryParams = new NameValueCollection
                                          {
                                              {"method", "getContexts"},
                                              {"key", currentIdentity.AuthKey}
                                          };
                    var response = _toodledoConnector.GetToodledoResponse(queryParams);
                    return ToodledoExtensions.AsContextList(response);
                }
            }
            throw new UnauthorizedAccessException("You are not signed in");
        }
        
        public List<Goal> GetGoals()
        {
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                var currentIdentity = Thread.CurrentPrincipal.Identity as ToodledoIdentity;

                if (currentIdentity != null)
                {
                    var queryParams = new NameValueCollection
                                          {
                                              {"method", "getGoals"},
                                              {"key", currentIdentity.AuthKey}
                                          };
                    var response = _toodledoConnector.GetToodledoResponse(queryParams);
                    return ToodledoExtensions.AsGoalList(response);
                }
            }
            throw new UnauthorizedAccessException("You are not signed in");
        }
    }
}